package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.common.entities.SiteComponent;
import com.uduemc.biso.node.core.common.udinpojo.ComponentBaidumapData;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.html.inter.HIComponentUdin;

@Component
public class HComponentBaidumapUdin implements HIComponentUdin {

	private static String name = "component_baidumap";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Override
	public StringBuilder html(SiteComponent siteComponent) {
		StringBuilder stringBuilder = new StringBuilder();
		String config = siteComponent.getComponent().getConfig();
		ComponentBaidumapData componentBaidumapData = ComponentUtil.getConfig(config, ComponentBaidumapData.class);
		if (componentBaidumapData == null || StringUtils.isEmpty(componentBaidumapData.getTheme())) {
			return stringBuilder;
		}
		String valueOf = String.valueOf(siteComponent.getComponent().getId());
		String id = "baidumap-id-" + DigestUtils.md5DigestAsHex(valueOf.getBytes());
		String en = valueOf;
		try {
			en = CryptoJava.en(valueOf);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String iframeSrc = siteUrlComponent
				.getPrivatePath(componentBaidumapData.getIframeSrc("/private/map/baidu.html", en));
		String width = componentBaidumapData.getWidth();
		String height = componentBaidumapData.getHeight();
		String textAlignStyle = componentBaidumapData.getTextAlignStyle();

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("comid", siteComponent.getComponent().getId());
		mapData.put("id", id);
		mapData.put("iframeSrc", iframeSrc);
		mapData.put("width", width);
		mapData.put("height", height);
		mapData.put("baidumapStyle", textAlignStyle);

		StringWriter render = basicUdin.render(name, "baidumap_" + componentBaidumapData.getTheme(), mapData);
		stringBuilder.append(render);
		return stringBuilder;
	}

}
